package com.link.play.fit.ai.utils

import android.os.Build
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.kv.AuthCache
import com.link.play.fit.ai.store.CloudStore
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.Locale
import java.util.TimeZone

object DeviceHelps {

    private val deviceName by lazy(LazyThreadSafetyMode.NONE) {
        getDeviceNames()
    }

    fun init() {
        MainScope().launch(CoroutineExceptionHandler { _, _ -> } + Dispatchers.IO) {
            deviceName
            getGoogleAdvertiserId()
        }
    }

    private fun getGoogleAdvertiserId() {
        try {
            val googleAdvertiserId = AdvertisingIdClient.getAdvertisingIdInfo(AppX.context).id ?: ""
            if (googleAdvertiserId.isNotEmpty())
                AuthCache.googleAdvertiserId = googleAdvertiserId
        } catch (e: Exception) {
            LogX.d("DeviceHelps", "getGoogleAdvertiserId error: ${e.localizedMessage}")
        }
    }

    private fun getDeviceNames(): String {
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        val flag = model.lowercase(Locale.getDefault())
            .startsWith(manufacturer.lowercase(Locale.getDefault()))

        val deviceName = if (flag) {
            if (model.isNullOrEmpty()) {
                model
            } else {
                model.substring(0, 1)
                    .uppercase(Locale.getDefault()) + model.substring(1)
                    .lowercase(Locale.getDefault())
            }

        } else {
            val ss = if (manufacturer.isNullOrEmpty()) {
                manufacturer
            } else {
                manufacturer.substring(0, 1)
                    .uppercase(Locale.getDefault()) + manufacturer.substring(1)
                    .lowercase(Locale.getDefault())
            }
            "$ss $model"
        }
        return deviceName
    }

    // 获取配置参数
    fun getConfigParams(): JSONObject {
        val packageName = GlobalConfig.PACKAGE_NAME
        val jsonObject = JSONObject()
        jsonObject.put("${packageName}_3", deviceName)//手机型号
        jsonObject.put("${packageName}_4", Build.MANUFACTURER)//手机厂商
        jsonObject.put("${packageName}_5", Build.VERSION.SDK_INT)//android系统版本号
        jsonObject.put("${packageName}_8", AppX.versionName)//APP版本号，如：1.1.2
        jsonObject.put("${packageName}_9", GlobalConfig.uid)//Android id
        jsonObject.put(
            "${packageName}_10",
            AuthCache.googleAdvertiserId
        )//Google advertiser id
        jsonObject.put("${packageName}_13", "android")//platform  默认android
        jsonObject.put("${packageName}_14", AppX.versionCode)//android版本，如：13
        jsonObject.put("${packageName}_15", "google")
        jsonObject.put("${packageName}_24", BuildConfig.BUILD_TYPE)//环境
        val timeZone: TimeZone = TimeZone.getDefault()
        jsonObject.put("${packageName}_34", timeZone.id) // 手机本地时区，值如下格式：America/New_York
        jsonObject.put("${packageName}_35", CloudStore.uid) // 谷歌一键登录的uid，但是这个uid可能和本地生成的一样，因为可能没登录
        return jsonObject
    }
}